package club.xiaojiawei.array;

/**
 * @author 肖嘉威
 * @version 1.0
 * @date 5/3/22 6:21 PM
 * @question 1004. 最大连续1的个数 III
 * @description 给定一个二进制数组 nums 和一个整数 k，如果可以翻转最多 k 个 0 ，则返回 数组中连续 1 的最大个数 。
 */
public class LongestOnes1004 {

    public static void main(String[] args) {
        int[] nums = {0,0,1,1,0,0,1,1,1,0,1,0,0,1,1,1,1,1,0};
        int result = longestOnes3(nums, 1);
        System.out.println(result);
    }

    /**
     * 滑动窗口法
     * @param nums
     * @param k
     * @return
     */
    public static int longestOnes(int[] nums, int k) {
        if (nums.length <= k){
            return nums.length;
        }
        int maxLength = 0, l = 0, r = 0;
        for (; r < nums.length; r++){
            if (nums[r] == 0){
                if (k == 0){
                    maxLength = Math.max(maxLength, r - l);
                    while (nums[l] != 0){
                        l++;
                    }
                    l++;
                }else {
                    k--;
                }
            }
        }
        maxLength = Math.max(maxLength, r - l);
        return maxLength;
    }

    /**
     * 民间-滑动窗口法
     * @param nums
     * @param k
     * @return
     */
    public static int longestOnes2(int[] nums, int k) {
        int n = nums.length;
        int l = 0;
        int r = 0;
        int max = 0;
        while (r < n) {
            if (nums[r] == 0) {
                k--;
            }
            while (k < 0) {
                if (nums[l++] == 0) {
                    k++;
                }
            }
            max = Math.max(max,r - l + 1);
            r++;
        }
        return max;
    }

    /**
     * 官方-二分查找
     * @param nums
     * @param k
     * @return
     */
    public static int longestOnes3(int[] nums, int k) {
        int n = nums.length;
//        记录有几个0
        int[] P = new int[n + 1];
        for (int i = 1; i <= n; ++i) {
            P[i] = P[i - 1] + (1 - nums[i - 1]);
        }

        int ans = 0;
        for (int right = 0; right < n; ++right) {
            int left = binarySearch(P, P[right + 1] - k);
            ans = Math.max(ans, right - left + 1);
        }
        return ans;
    }

    public static int binarySearch(int[] P, int target) {
        int low = 0, high = P.length - 1;
        while (low < high) {
            int mid = (high - low) / 2 + low;
            if (P[mid] < target) {
                low = mid + 1;
            } else {
                high = mid;
            }
        }
        return low;
    }

}
